package alarm.ruiqi.com.alarm_pro.options;


import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.lidroid.xutils.util.LogUtils;
import com.nineoldandroids.view.ViewHelper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import alarm.ruiqi.com.alarm_pro.R;
import alarm.ruiqi.com.alarm_pro.options.alarm.AlarmInfoFragment;
import alarm.ruiqi.com.alarm_pro.options.base.BaseActivity;
import alarm.ruiqi.com.alarm_pro.options.head.GeneralHeadFragment;
import alarm.ruiqi.com.alarm_pro.options.head.GeneralHeadFragment.OnFragmentInteractionListener;
import alarm.ruiqi.com.alarm_pro.options.tabs.GeneralTabFragment;
import alarm.ruiqi.com.alarm_pro.options.weather_forcast.WeatherForcastFragment;
import alarm.ruiqi.com.alarm_pro.options.webview.GeneralWebviewFragment;
import alarm.ruiqi.com.alarm_pro.service.TabsServiceImpl;
import alarm.ruiqi.com.alarm_pro.utils.Constant;


public class MainActivity extends BaseActivity implements OnFragmentInteractionListener {


    private DrawerLayout mDrawerLayout;
    private GeneralHeadFragment mHeadFragment;
    private MainActivityInterInteractionListener mainActivityInterInteractionListener;
    private Fragment mMainFragment; //当前主页面的fragment
    private NavigationView mNavigationView;
    private onMenuSelected mMenuSelectListenr;
    private MenuItem mSelectMenu;

    //region 生命周期相关方法

    //region 生命周期
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.activity_main_slidingmenu);
        initView();
        initHead();
        initDrawer();
        initEvents();
        action2Main();
    }
    //endregion


    //===================== 生命周期方法 ============================
    //默认主界面
    private void action2Main() {
        switchContent(GeneralWebviewFragment.newInstance(getResources().getString(R.string.main_url)), false);
        addMenu();

    }

    public void addMenu() {
        mHeadFragment.togglrRightDrawable(true);
        mHeadFragment.addRightDrawable(R.drawable.fab_add, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchContent(new AlarmInfoFragment(), true);
                mNavigationView.getMenu().getItem(0).setChecked(true);
            }
        });
        mHeadFragment.setHeadText(null);
    }

    private void initHead() {
        mHeadFragment = (GeneralHeadFragment) getFragmentManager().findFragmentById(R.id.main_head);
    }

    private void initDrawer() {
        mNavigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {

                    Snackbar snac = Snackbar.make(mDrawerLayout, "", Snackbar.LENGTH_LONG).setAction("Action", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(
                                    MainActivity.this,
                                    "Toast comes out",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });

                    @Override
                    public boolean onNavigationItemSelected(final MenuItem menuItem) {
                        mSelectMenu = menuItem;
                        snac.setText(menuItem.getTitle());
                        menuItem.setChecked(true);
                        mDrawerLayout.closeDrawers();
                        snac.show();
                        return true;
                    }
                });
    }

    /**
     * 初始化事件
     */
    private void initEvents() {
        mMenuSelectListenr = new onMenuSelected() {
            @Override
            public void onMenuSelected(MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.nav_睡前:
                        if (!(mMainFragment instanceof GeneralTabFragment)) {
                            getSupportFragmentManager().popBackStackImmediate();
                            List<Fragment> baseFragments = new ArrayList<>();
                            List<String> titles = new ArrayList<>();
                            titles = Arrays.asList(MainActivity.this.getResources().getStringArray(R.array.tab_title));
                            String urls[] = new TabsServiceImpl(getApplicationContext()).getTab_Urls();
                            for (int i = 0; i <titles.size(); i++) {
                                GeneralWebviewFragment fragment = GeneralWebviewFragment.newInstance(urls[i]);
                                baseFragments.add(fragment);
                            }
//                            baseFragments.add(0,new MusicFragment());
//                            baseFragments.remove(2);
                            switchContent(GeneralTabFragment.newInstance(baseFragments, titles), true);
                        }

                        break;
                    case R.id.nav_起床:
                                /* FragmentTransaction t = MainActivity.this.getFragmentManager()
                                        .beginTransaction();
                                mMainFragment = new AlarmInfoFragment();
                                t.replace(R.id.main_content, mMainFragment).addToBackStack(mMainFragment.getClass().getSimpleName());
                                t.commit();*/
                        if (!(mMainFragment instanceof AlarmInfoFragment)) {
                            getSupportFragmentManager().popBackStackImmediate();
                            switchContent(new AlarmInfoFragment(), true);
                        }

                        break;
                    case R.id.nav_天气预报:
                        if (!(mMainFragment instanceof WeatherForcastFragment)) {
                            getSupportFragmentManager().popBackStackImmediate();
                            switchContent(new WeatherForcastFragment(), true);
                        }


                        break;
                }
            }
        };

        mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                setForSlidingMenu(drawerView, slideOffset);
                setForMenuDrawable(slideOffset);
                if (mainActivityInterInteractionListener != null) {
                    mainActivityInterInteractionListener.onDrawerSlide(-drawerView.getMeasuredWidth() * (slideOffset));
                }
            }

            @Override
            public void onDrawerOpened(View drawerView) {
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                if (mSelectMenu != null && mMenuSelectListenr != null) {
                    mMenuSelectListenr.onMenuSelected(mSelectMenu);
                }
                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,
                        Gravity.RIGHT);
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }

            /**
             * 设置SlidingMenu
             * @param drawerView
             * @param slideOffset
             */
            private void setForSlidingMenu(View drawerView, float slideOffset) {
                View mContent = mDrawerLayout.getChildAt(0);
                View mMenu = drawerView;
                float scale = 1 - slideOffset;
                float rightScale = 0.8f + scale * 0.2f;
                float leftScale = 1 - 0.3f * scale;

                /*============ view 相关效果 =======================*/
                ViewHelper.setScaleX(mMenu, leftScale);
                ViewHelper.setScaleY(mMenu, leftScale);
                ViewHelper.setAlpha(mMenu, 0.8f + 0.2f * (1 - scale));
                ViewHelper.setTranslationX(mContent,
                        mMenu.getMeasuredWidth() * (1 - scale));
                ViewHelper.setPivotX(mContent, 0);
                ViewHelper.setPivotY(mContent,
                        mContent.getMeasuredHeight() / 2);
                mContent.invalidate();

                ViewHelper.setScaleX(mContent, rightScale);
                ViewHelper.setScaleY(mContent, rightScale);

                // ViewHelper.setTranslationX(mAddButton, );
            }

            private void setForMenuDrawable(float slideOffset) {
                if (slideOffset >= .995) {
                    mHeadFragment.getmDrawerArrowDrawable().setFlip(true);
                } else if (slideOffset <= .005) {
                    mHeadFragment.getmDrawerArrowDrawable().setFlip(false);
                }
                mHeadFragment.getmDrawerArrowDrawable().setParameter(slideOffset);
            }
        });
    }

    private void initView() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.main_drawerLayout);
        mNavigationView = (NavigationView) findViewById(R.id.nv_main_navigation);

        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,
                Gravity.RIGHT);
    }


    public void hideHead() {
        getFragmentManager().beginTransaction().hide(mHeadFragment).commit();
    }

    //*********************** OnFragmentInteractionListener ************************************
    @Override
    public void onDrawerIndicatorChange(View v) {
        //打开或关闭抽屉
        if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            mDrawerLayout.openDrawer(GravityCompat.START);
        }
    }
    //endregion

    //region 用于与fragment的事件交互
    //*********************** Activity interface ************************************//
    //                  用于与fragment的事件交互    slideOffset = 屏幕*比例             //
    //*********************** Activity interface ************************************//
    public interface MainActivityInterInteractionListener {
        void onDrawerSlide(float slideOffset);
    }


    public void setMainActivityInterInteractionListener(MainActivityInterInteractionListener mainActivityInterInteractionListener) {
        this.mainActivityInterInteractionListener = mainActivityInterInteractionListener;
    }
    //endregion

    //region view 触摸事件
    //===============================view 触摸事件 ===================================================
    private long mExitTime = 0;

    @Override
    public void onBackPressed() {


        long mNowTime = System.currentTimeMillis();//获取第一次按键时间
        if ((mNowTime - mExitTime) > 2000) {//比较两次按键时间差
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = mNowTime;
        } else {//退出程序
            this.finish();
            System.exit(0);
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //onKeyDown 与parentActivity 的dispatchKeyEvent 冲突
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            //关闭抽屉
            if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) {
                mDrawerLayout.closeDrawer(GravityCompat.START);
                return true;
            }
            //网页内容返回
            if (mMainFragment instanceof GeneralWebviewFragment && ((GeneralWebviewFragment) mMainFragment).canGoBack()) {
                ((GeneralWebviewFragment) mMainFragment).goBack();
                return true;
            }
            //回退栈
            android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
            int backCount = fm.getBackStackEntryCount();
            if (backCount > 0) {
                mMainFragment = fm.getFragments().get(backCount-1);
                return onBackKeyDown(backCount, event);
            } else {

                return super.dispatchKeyEvent(event);
            }

        } else {
            return super.dispatchKeyEvent(event);
        }
    }

    public boolean onBackKeyDown(int backStackCount, KeyEvent event) {
        if (backStackCount ==1 ) {
            //去除menu后重新添加menu布局（去除选中状态，setchecked（false）无效）
            mNavigationView.getMenu().removeGroup(0);
            mNavigationView.inflateMenu(R.menu.menu_drawer);
//            mSelectMenu.setChecked(false);
            mSelectMenu = null;
        }
        return getSupportFragmentManager().popBackStackImmediate();
    }

    public void switchContent(Fragment fragment, boolean addToBackStack,
                              Object... params) {
        if (fragment != null) {
            if (params != null) {
                Bundle args = fragment.getArguments();
                if (args == null)
                    args = new Bundle();
                args.putSerializable(Constant.SwitchContent_SAVE_KEY, params);
                fragment.setArguments(args);
            } else {
                LogUtils.i("目标ParentFragment未传递参数");
            }
            FragmentTransaction t = getSupportFragmentManager()
                    .beginTransaction();
            t.replace(R.id.main_content, fragment);
            if (addToBackStack) {
                t.addToBackStack(fragment.getClass().getSimpleName());
            }
            // 给内容Fragment赋值，并在onSaveInstanceState时保存这个Fragment
            mMainFragment = fragment;
            t.commit();
        } else {
            Log.e(this.getClass().getSimpleName(), "目标ParentFragment为空");
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.i(this.getClass().getSimpleName() + "onActivityResult");
        mMainFragment.onActivityResult(requestCode, resultCode, data);
    }
    //endregion

    //region 成员对象的公有方法
    //=============================== 成员对象的公有方法===========================

    public GeneralHeadFragment getHeadFragment() {
        return mHeadFragment;
    }

    public DrawerLayout getmDrawerLayout() {
        return mDrawerLayout;
    }

    public Fragment getMainFragment() {
        return mMainFragment;
    }
    //endregion

    //region drawer 与  菜单交互接口
    //============================== drawer 与  菜单交互接口 ===============================

    public interface onMenuSelected {
        void onMenuSelected(MenuItem item);


    }
    //endregion
}
